package com.example.controller;

import com.example.constant.Constants;
import com.example.model.UserInfo;
import com.example.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: bjc
 * Date: 2025-07-19
 * Time: 14:32
 */
@RequestMapping("/user")
@RestController
public class UserInfoController {
    @Autowired
    private UserService userService;

    /**
     * 登录接口实现
     * @param userInfo 用户对象
     * @return true或false
     */
    @PostMapping("/login")
    public Boolean login(UserInfo userInfo, HttpSession session){
        //1.参数校验是否存在空数据
        if(!StringUtils.hasLength(userInfo.getUserName()) || !StringUtils.hasLength(userInfo.getPassword())){
            return false;
        }
        //2.校验用户名和密码
        //2.1 接收到逻辑层返回的数据库信息
        UserInfo userInfoFromMysql = userService.queryUserInfoByUserName(userInfo.getUserName());
        //2.2 判断数据库信息是否为空
        if(userInfoFromMysql == null){
            return false;
        }
        //2.3 判断用户名是否存在，不存在则返回false
        if(!StringUtils.hasLength(userInfoFromMysql.getUserName())){
            return false;
        }
        //2.4 用户存在，校验密码是否正确
        if(!userInfo.getPassword().equals(userInfoFromMysql.getPassword())){
            return false;
        }
        //3.校验密码相等
        //返回响应结果，使用session存储数据
        session.setAttribute(Constants.USER_SESSION_KEY,userInfoFromMysql);
        return true;
    }
}
